import { Component } from 'react';

import {Toast, Group, Boxs, Button} from 'saltui';
const { IconButton } = Button;
const { HBox, Box, VBox } = Boxs;
import { Map } from 'react-amap';
import DB from '../../../app/db';
import './PageHome.less';

let fun ;

export default class PageHome extends Component {

 constructor(props) {
    super(props);

    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    this.state = {
      singedInfoId: "",
      applyRecordId: this.props.params.applyRecordId,
      isSigned: "",
      qrcodeTime: "",
      positionTime: "",
      showTime: "",
      address: "",
      isArrivals: false,
      longitude: "",
      latitude: "",
      signedType: "1",
      signedRange: "",
      addressList: [],
      geolocation: null
    };

    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });
    this.amapEvents = {
      created: (mapInstance) => {
          AMap.plugin('AMap.Geolocation', function() {
            var geolocation = new AMap.Geolocation({
                timeout: 10000,          //超过10秒后停止定位，默认：5s
                buttonPosition:'LB',    //定位按钮的停靠位置
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                noGeoLocation: 1,
                showButton:false
            });
            mapInstance.addControl(geolocation);
            t.getPosition(geolocation);
            t.setState({
              geolocation:geolocation
            });
          })
      }
    };
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  componentDidMount (){
    //当办理后返回首页回调
    let t = this;
    document.addEventListener('resume', function() {
       t.refreshSignData();
    });
    var page_title = "会议签到";
    $("title").text(page_title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : page_title,//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: page_title,
            icon: '',
            actionmenu: {}
        },
      });
    }
  }

  //视图渲染前执行
  componentWillMount() {
    let t = this;
    fun = setInterval(()=>{t.initTime()},1000);
    //alert("t.state.applyRecordId:"+t.state.applyRecordId);
    //查询签到信息
    var params = {applyRecordId: t.state.applyRecordId};
    DB.SomeModuleAPI.getSignedInfo(params).then((content) => {
      //alert(JSON.stringify(content));
      var singedInfo = content.singedInfo;
      if(singedInfo != null){
        var isSigned = singedInfo.isSigned;
        if(isSigned == null){
          isSigned = "";
        }
        var qrcodeTime = "";
        if(singedInfo.qrcodeTime != null){
          qrcodeTime = singedInfo.qrcodeTime.substring(0,19);
        }
        //alert("qrcodeTime:"+qrcodeTime);
        var positionTime = "";
        if(singedInfo.positionTime != null){
          positionTime = singedInfo.positionTime.substring(0,19);
        }
        t.setState({
          isSigned: isSigned,
          qrcodeTime: qrcodeTime,
          positionTime: positionTime,
          singedInfoId: singedInfo.id
        });
      }
      var record = content.record;
      t.setState({
        signedType: record.signedType,
        signedRange: record.signedRange,
        addressList: content.addressList
      });
      // t.getPosition(record.signedRange);
    }).catch((error) => {
      alert("error:"+error);
    });
  }

  //移除组件以后
  componentWillUnmount(){
     clearInterval(fun); 
  }

  //显示签到时间
  initTime(){
    let showTime =  new Date().format("HH:mm:ss");
    this.setState({
      showTime : showTime
    });
  }

  //定位
  getPosition(geolocation){
    let t = this;
    var isArrivals = false;
    geolocation.getCurrentPosition(function(status,result){
      if(status=='complete'){
        var position = result.position;
        if(position != null){
          var positions = (position + "").split(',');
          if(positions.length == 2){
            isArrivals = t.isInSignedRange(positions[0], positions[1]);
            if(isArrivals){
              t.setState({
                isArrivals: isArrivals,
                address: result.formattedAddress,
                longitude: positions[0],
                latitude: positions[1]
              });
            }
          }
        }
      }else{
          console.log('定位失败');
          console.log('失败原因排查信息:'+result.message);
          alert(result.message);
      }
    });
  }

  //定位
  // getPosition(effectRange){
  //   let t = this;
  //   var range = parseInt(effectRange);
  //   var isArrivals = false;
  //   var thirdMenuType = getLoginUserInfo().thirdMenuType;
  //   if(thirdMenuType=='DING'){
  //     dd.device.geolocation.get({
  //       targetAccuracy : range,
  //       coordinate: 1,
  //       withReGeocode: true,
  //       useCache: true, //默认是true，如果需要频繁获取地理位置，请设置false
  //       onSuccess : function(result) {
  //         var realLongitude = result.longitude;
  //         var realLatitude = result.latitude;
  //         isArrivals = t.isInSignedRange(realLongitude, realLatitude);
  //         if(isArrivals){
  //           t.setState({
  //             isArrivals: isArrivals,
  //             address: result.address,
  //             longitude: realLongitude,
  //             latitude: realLatitude
  //           });
  //         }
  //       },
  //       onFail : function(err) {
  //       }
  //     });
  //   }else if(thirdMenuType=='WX'){
  //     wx.getLocation({
  //         type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
  //         success: function (res) {
  //             var realLatitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
  //             var realLongitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
  //             isArrivals = t.isInSignedRange(realLongitude, realLatitude);
  //             if(isArrivals){
  //               t.setState({
  //                 isArrivals: isArrivals,
  //                 address: res.address,
  //                 longitude: realLongitude,
  //                 latitude: realLatitude
  //               });
  //             }
  //         }
  //     });
  //   }else if(thirdMenuType=='MH'){
  //     emp.getLocation({
  //         type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
  //         success: function (res) {
  //             var realLatitude = res.latitude ; // 纬度，浮点数，范围为90 ~ -90
  //             var realLongitude = res.longitude ; // 经度，浮点数，范围为180 ~ -180。
  //             isArrivals = t.isInSignedRange(realLongitude, realLatitude);
  //             if(isArrivals){
  //               t.setState({
  //                 isArrivals: isArrivals,
  //                 address: res.address,
  //                 longitude: realLongitude,
  //                 latitude: realLatitude
  //               });
  //             }
  //         }
  //     });
  //   }
  // }

  refreshSignPosition(){
    document.getElementById("reshshPosIcon").className = 'iconfont icon-refresh t-FCgreen t-rotate-360';
    this.getPosition(this.state.geolocation);
    //this.getPosition(this.state.signedRange);
    setTimeout(function(){
      document.getElementById("reshshPosIcon").className = 'iconfont icon-refresh t-FCgreen';
    },1000);
  }

  refreshSignData(){
    let t = this;
    var params = {applyRecordId: t.state.applyRecordId};
    DB.SomeModuleAPI.getSignedInfo(params).then((content) => {
      var singedInfo = content.singedInfo;
      if(singedInfo != null){
        var isSigned = singedInfo.isSigned;
        if(isSigned == null){
          isSigned = "";
        }
        var qrcodeTime = "";
        if(singedInfo.qrcodeTime != null){
          qrcodeTime = singedInfo.qrcodeTime.substring(0,19);
        }
        var positionTime = "";
        if(singedInfo.positionTime != null){
          positionTime = singedInfo.positionTime.substring(0,19);
        }
        t.setState({
          isSigned: isSigned,
          qrcodeTime: qrcodeTime,
          positionTime: positionTime,
          singedInfoId: singedInfo.id
        });
      }
    }).catch((error) => {
    });
  }

    //地址微调
  getPositionPOI(){
    let t = this;
    var range = parseInt(t.state.signedRange);
    dd.biz.map.search({
      latitude: t.state.latitude, // 纬度
      longitude: t.state.longitude, // 经度
      scope: 100, // 限制搜索POI的范围；设备位置为中心，scope为搜索半径
      onSuccess: function (poi) {
        t.setState({
          latitude : poi.latitude,
          longitude : poi.longitude,
          address : poi.city + poi.adName + poi.snippet + poi.title ,
        });
      },
      onFail: function (err) {
        let e = JSON.stringify(err);
        Toast.show({type: 'light',content: e+'定位失败！',});
      }
    });
  }

  scanQrcode(){
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    let ipPort = getLoginUserInfo().contextPageUrl;
    //第三方标识：DING（钉钉），WX（企业微信），MH（移动门户）
    if(thirdMenuType=='DING'){
      dd.biz.util.scan({
        type: "qrCode" , // type 为 all、qrCode、barCode，默认是all。
        onSuccess: function(data) {
          pageSkipDirectly(ipPort + data.text);
        },
        onFail : function(err) {}
      })
    }else if(thirdMenuType=='WX'){
      wx.scanQRCode({
        desc: 'scanQRCode desc',
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
        success: function(res) {
          //alert("ipPortres.resultStr:"+ipPort + res.resultStr);
          pageSkipDirectly(ipPort + res.resultStr);
        },
        error: function(res) {
            if (res.errMsg.indexOf('function_not_exist') > 0) {
                alert('版本过低请升级')
            }
        }
      });
    }else if(thirdMenuType=='MH'){
      !!emp&&emp.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由App处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          pageSkipDirectly(ipPort + res.resultStr);
        }
      });
    }
  }

  showResultMsg(status){
    if(status == "1"){
      Toast.show({
        type: 'error',
        content: '未到签到时间',
        onHide: function () {
        }
      });
    }else if(status == "0"){//成功签到
      Toast.show({
        type: 'success',
        content: '签到成功'
      });

      setTimeout(() => {this.refreshSignData()}, 1000);
    }else if(status == "2"){//会议结束
      Toast.show({
        type: 'success',
        content: '会议已结束'
      });
    }else if(status == "3"){
      Toast.show({
        type: 'success',
        content: '会议已取消'
      });
    }else if(status == "-1"){
      Toast.show({
        type: 'text',
        content: '您没有参加该会议',
        onHide: function () {
        }
      });
    }
  }

  //是否在签到范围内
  isInSignedRange(realLongitude, realLatitude){
    let t = this;
    var addressList = t.state.addressList;
    var signedRange = parseInt(t.state.signedRange);
    var flag = false;
    for(var i=0; i<addressList.length; i++){
      var recordLongitude = addressList[i].longitude;
      var recordLatitude = addressList[i].latitude;
      // alert("获取精度：" + realLongitude + ";数据库精度：" + recordLongitude + ";获取纬度：" + realLatitude + ";数据库纬度：" + recordLatitude);
      var length = t.countDistance(realLongitude,realLatitude,recordLongitude,recordLatitude);
      // alert(length + " ; " + signedRange);
      if(length <= signedRange){
        flag = true;
        break;
      }
    }
    return flag;
  }

  //定位签到
  positionSigned(){
    let t = this;
    //t.getPosition(t.state.signedRange);
    var realLongitude = t.state.longitude, realLatitude = t.state.latitude;
    var flag = this.isInSignedRange(realLongitude, realLatitude);
    if(flag){
      let param = {id: t.state.applyRecordId, signType: "1", signedAddress: t.state.address};
      DB.SomeModuleAPI.userSigned(param).then((content) => {
          t.showResultMsg(content.status);
        }).catch((error) => {
          if(typeof(error.errorMsg) == 'undefined'){
            Toast.show({
            type: 'error',
            content: '提交出错'
             });
          }else{
            Toast.show({
            type: 'error',
            content: error.errorMsg
             });
          }
        });
      }else{
        Toast.show({
          type: 'error',
          content: '不在签到范围内',
          onHide: function () {
          }
        });
        return;
      }
  }

  //经纬度坐标之间的距离，Haversine公式
  countDistance(realLongitude,realLatitude,recordLongitude,recordLatitude){
    if(realLongitude != undefined && realLongitude != null && realLatitude != undefined && realLatitude != null &&
      recordLongitude != undefined && recordLongitude != null && recordLatitude != undefined && recordLatitude != null){
        const EARTH_RADIUS = 6378.137;//km 赤道半径
        var radLat1 = realLatitude*Math.PI / 180.0;
        var radLat2 = recordLatitude*Math.PI / 180.0;
        var reLong1 = realLongitude*Math.PI / 180.0;
        var reLong2 = recordLongitude*Math.PI / 180.0;
        var a = Math.abs(radLat1 - radLat2);
        var b = Math.abs(reLong1 - reLong2);
        var length = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        length = length * EARTH_RADIUS;
        length = Math.round(length * 10000) / 10;
        return length;
    }else{
      return -1;
    }
  }

  getWinHeight(){
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    var winHeight = '';
    if(isAndroid==true){
        winHeight = $(window).height() + 'px';
    }else if(isiOS==true){
        var high = window.screen.availHeight - 46;
        winHeight = high + 'px';
    }
    return winHeight;
  }

  render() {
    let t = this;
    let hight = t.getWinHeight();
    return (
      <div>
        <div style={{width: '100vw', height:hight, position:'absolute', zIndex:-10 }}>
          <Map zoom={17} events={this.amapEvents}/>
        </div>
        <div style={{height:hight, position:'relative', background:'#fff', opacity: 1}}>
          <Group.List className={t.state.signedType=="2" ? "":"t-DN"}>
            <HBox vAlign="center" className="t-field-box">
              <Box className="t-field-layout-h-label">扫码签到</Box>
              <Box flex={1}>{t.state.isSigned.indexOf("s")>=0 ? "已签到" : "未签到"}</Box>
              <Box className="t-FS16 t-LH2" >{t.state.qrcodeTime}</Box>
            </HBox>
          </Group.List>
          <Group.List>
            <HBox vAlign="center" className="t-field-box">
              <Box className="t-field-layout-h-label">定位签到</Box>
              <Box flex={1}>{t.state.isSigned.indexOf("d")>=0 ? "已签到" : "未签到"}</Box>
              <Box className="t-FS16 t-LH2" >{t.state.positionTime}</Box>
            </HBox>
          </Group.List>
          <Group.List>
            <div className="t-BCf t-P16">
              <VBox className="dd-attendance-time" onClick={t.positionSigned.bind(this)}>
                <Box className="t-FS26">签到</Box>
                <Box className="t-FS14 t-LH1_4">{t.state.showTime}</Box>
              </VBox>
              <HBox vAlign="center" className="t-P16 t-LH1_8 dd-cell">
                <Box flex={1}>{t.state.isArrivals?"已在签到范围内:":"不在签到范围内，请刷新定位"}{t.state.address}</Box>
                <Box onClick={()=>{t.refreshSignPosition()}}><i className="iconfont icon-refresh t-FCgreen" id="reshshPosIcon"></i></Box>
              </HBox> 
              {/*<Box className="t-FAC t-FCgreen">
                <span className="t-MR10" onClick={t.getPositionPOI.bind(this)}>地址微调</span>
              </Box>*/}
            </div>
          </Group.List>
          <IconButton  className={t.state.signedType=="2" ? "add-new-page t-BCddblue":"t-DN"} onClick={this.scanQrcode.bind(this)}><i className="iconfont icon-scan t-FCf"></i></IconButton>
        </div>
      </div>
    );
  }
}


